package com.nd.android.u.ui.activity.chat_relative_image;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore.MediaColumns;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.common.StarAppConst;
import com.common.allCommon.TextHelper;
import com.common.android.ui.gif.BitmapToolkit;
import com.common.android.utils.ToastUtils;
import com.common.android.utils.task.progressTask.ProgressTask;
import com.common.utils.StarAppUtils;
import com.common.widget.CommonActivityTitle;
import com.common.widget.CommonActivityTitle.TitleBtnCallback;
import com.nd.android.u.allCommonUtils.FileHelper;
import com.nd.android.u.ui.R;
import com.product.android.ui.activity.BaseReceiverFragmentActivity;

public class SendImageActivity extends BaseReceiverFragmentActivity {

	/** 上下文 */
	private Activity mActivity;

	/** 顶部Title */
	private CommonActivityTitle mCommonActivityTitle;

	private ImageView imgView;
	private TextView dimensionsText;
	private TextView sizeText;
	private TextView nameText;
	private File mFile;
	private static final int SUCCESS = 0;
	private static final int MAX_BITMAP_SIZE = 480;
	private static final int MAX_BITMAP_SIZE2 = 1280;
	private TextView labelText;
	private ProgressDialog mDialog;
	private TextView tvCompress;
	private boolean mbIsThumbnail = true;
	private File mThumbnailTempFile;
	private Bitmap mThumbnail;
	private Uri mPostUri;
	private int mThumbnailSize = 0;
	private String mOriSizeString = "";
	private Cursor mCursor;
	private boolean isCapture;

	@Override
	protected boolean _onCreate(Bundle savedInstanceState) {
		mActivity = this;
		if (super._onCreate(savedInstanceState)) {
			this.setContentView(R.layout.image_look);
			Bundle bundle = this.getIntent().getExtras();
			if (bundle != null) {
				if (bundle.containsKey("uri")) {
					mPostUri = bundle.getParcelable("uri");
					isCapture=bundle.getBoolean("isCapture");
				} else {
					return false;
				}
			}
			initComponent();
			initEvent();
			return true;
		}
		return false;
	}

	protected void onStart() {
		super.onStart();
		new LoadingBitmap(mActivity, R.string.image_loading).execute();
		// if (!getBitmapFromUri()){
		// ToastUtils.display(R.string.image_sendimageactivity);
		// finish();
		// return;
		// }
		// if (mThumbnail==null){
		// ToastUtils.display(R.string.image_sendimageactivity);
		// finish();
		// return;
		// }
		// initComponentValue();
	}

	protected void initComponent() {
		super.initComponent();
		mCommonActivityTitle = (CommonActivityTitle) findViewById(R.id.common_title);
		imgView = (ImageView) this.findViewById(R.id.image_look_img);
		dimensionsText = (TextView) this
				.findViewById(R.id.image_look_text_dimensions);
		sizeText = (TextView) this.findViewById(R.id.image_look_text_size);
		nameText = (TextView) this.findViewById(R.id.image_look_text_name);
		labelText = (TextView) this.findViewById(R.id.image_look_text_lable);
		tvCompress = (TextView) this.findViewById(R.id.tvCompress);
		tvCompress.setVisibility(View.VISIBLE);
		mCommonActivityTitle.setTitleTextTypeface(StarAppConst.getInstance()
				.getLTXTypeface(), false);
		StarAppUtils.setViewTypeFace(sizeText, false);
		StarAppUtils.setViewTypeFace(nameText, false);
		StarAppUtils.setViewTypeFace(labelText, false);
		StarAppUtils.setViewTypeFace(tvCompress, false);
	}

	protected void initEvent() {
		super.initEvent();
		mCommonActivityTitle.setTitleBtnCallback(mTitleBtnCallback);
		tvCompress.setOnClickListener(mOnClickListener);
	}

	/**
	 * 顶部Title按钮监听
	 */
	private TitleBtnCallback mTitleBtnCallback = new TitleBtnCallback() {

		@Override
		public void onBtnClick(final int clickType) {
			if (clickType == CommonActivityTitle.ON_LEFT_CLICK_CALL_BACK) {
				finish();
			} else {
				sendImage();
			}

		}
	};

	private OnClickListener mOnClickListener = new OnClickListener() {
		@TargetApi(Build.VERSION_CODES.CUPCAKE)
		@Override
		public void onClick(View v) {
			mbIsThumbnail = mbIsThumbnail ? false : true;
			if (mbIsThumbnail) {
				tvCompress.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.btn_check_on, 0);
			} else {
				tvCompress.setCompoundDrawablesWithIntrinsicBounds(0, 0,
						R.drawable.btn_check_off, 0);
			}
			setImage();
		}
	};

	private void setImage() {
		nameText.setText(mFile.getName());
		if (mbIsThumbnail) {
			dimensionsText.setText(mThumbnail.getWidth() + "*"
					+ mThumbnail.getHeight());
			sizeText.setText(TextHelper.getFileLengthUnitKB(mThumbnailSize));
		} else {
			dimensionsText.setText(mOriSizeString);
			sizeText.setText(TextHelper.getFileLengthUnitKB(mFile.length()));
		}
	}

	private void packageBitmap() {
		File newFile = null;
		try {
			newFile = FileHelper.getDefaultImageFile(FileHelper.UPLOAD);
		} catch (IOException e) {
			mHandler.sendEmptyMessage(R.string.create_new_file);
			e.printStackTrace();
			return;
		}
		if (mbIsThumbnail) {
			// 发送缩略图
			if (!BitmapToolkit.saveBitmap(newFile, mThumbnail)) {
				mHandler.sendEmptyMessage(R.string.save_new_file);
				return;
			}
		} else {
			// 发送大图
//		    if (isCapture) {
		      //bug60219 mn
            String path = mFile.getPath();
            int start = path.lastIndexOf(".");
            String ext = "";
            if ((start > -1) && (start < (path.length() - 1))) {
                ext = path.substring(start + 1);
            }
            if (!TextUtils.isEmpty(ext) && !"gif".equals(ext.toLowerCase())) {
                int degree = BitmapToolkit.getDegree(mFile.getPath());
                Bitmap roBitmap=BitmapFactory.decodeFile(mFile.getPath());
                roBitmap = BitmapToolkit.rotateBitmap(roBitmap, degree);
                BitmapToolkit.saveBitmap(newFile, roBitmap);
                if (!roBitmap.isRecycled()) {
                    roBitmap.recycle();
                }
            }else {
                try {
                    FileHelper.copyFile(mFile, newFile);
                } catch (FileNotFoundException e) {
                    mHandler.sendEmptyMessage(R.string.save_new_file);
                    e.printStackTrace();
                    return;
                } catch (IOException e) {
                    mHandler.sendEmptyMessage(R.string.save_new_file);
                    e.printStackTrace();
                    return;
                }
            }
			
		}
		Uri fileUri = Uri.fromFile(newFile);
		Message message = new Message();
		message.what = SUCCESS;
		message.obj = fileUri;
		mHandler.sendMessage(message);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			super.handleMessage(msg);
			if (mDialog != null) {
				mDialog.dismiss();
			}
			if (msg.what != SUCCESS) {
				ToastUtils.display(SendImageActivity.this, msg.what);
				setResult(RESULT_CANCELED, getIntent());
				finish();
			} else {
				Uri mFileUri = (Uri) msg.obj;
				Intent intent = new Intent(Intent.ACTION_SEND, mFileUri);
				setResult(RESULT_OK, intent);
				finish();
			}
		};
	};

	private void sendImage() {
		mDialog = ProgressDialog.show(this,
				getResources().getString(R.string.in_progress), getResources()
						.getString(R.string.waiting));
		new Thread(new Runnable() {
			public void run() {
				packageBitmap();
			}
		}).start();
	}

	private boolean getBitmapFromUri() {
		if (mPostUri.getScheme().equals("content")) {
			String path = getRealPathFromURI(mPostUri);
			if (TextUtils.isEmpty(path)) {
				return false;
			}
			mFile = new File(path);
		} else {
			mFile = new File(mPostUri.getPath());
		}
		if (mFile == null || !mFile.exists()) {
			return false;
		}
		try {
			// 先根据允许发送的最大尺寸压缩图片
			compressBitmap(mFile.getAbsolutePath(), MAX_BITMAP_SIZE);
			if (mbIsThumbnail) {
				// 获取缩放后的图片的大小
				mThumbnailTempFile = new File(getFilesDir(), mFile.getName());
				BitmapToolkit.saveBitmap(mThumbnailTempFile, mThumbnail);
				mThumbnailSize = (int) mThumbnailTempFile.length();
				mThumbnailTempFile.delete();
			}
		} catch (OutOfMemoryError e) {
			ToastUtils.display(this, R.string.low_memory);
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 制作微缩图
	 */
	protected void compressBitmap(String filePath, int size) {
		Options mOptions = new BitmapFactory.Options();
		mOptions.inJustDecodeBounds = true;
		mOptions.inSampleSize = 1;
		BitmapFactory.decodeFile(filePath, mOptions);
		mOriSizeString = mOptions.outWidth + "*" + mOptions.outHeight;
		if (isCapture) {
		    mOriSizeString = mOptions.outHeight + "*" + mOptions.outWidth;
        }
		long maxSize = MAX_BITMAP_SIZE * MAX_BITMAP_SIZE;
		long nowSize = mOptions.outWidth * mOptions.outHeight;
		while (nowSize > maxSize) {
			mOptions.inSampleSize *= 2;
			nowSize = nowSize >> 2;
		}
		mOptions.inJustDecodeBounds = false;
		mThumbnail = BitmapFactory.decodeFile(filePath, mOptions);
		int degree = BitmapToolkit.getDegree(filePath);
		mThumbnail = BitmapToolkit.rotateBitmap(mThumbnail, degree);
		mbIsThumbnail = mOptions.inSampleSize > 1;
	}

	@TargetApi(Build.VERSION_CODES.CUPCAKE)
	protected void initComponentValue() {
		super.initComponentValue();
		labelText.setText(R.string.you_will_send_pic);
		if (mbIsThumbnail) {
			tvCompress.setCompoundDrawablesWithIntrinsicBounds(0, 0,
					R.drawable.btn_check_on, 0);
		} else {
			// 缩略图和原图一样大，不需要压缩发送
			tvCompress.setVisibility(View.GONE);
		}
		imgView.setImageBitmap(mThumbnail);
		setImage();
	}

	protected String getRealPathFromURI(Uri contentUri) {
		String[] proj = { MediaColumns.DATA };
		if (mCursor == null) {
			mCursor = getContentResolver().query(contentUri, proj, null, null,
					null);
		}
		if (mCursor != null) {
			int column_index = mCursor.getColumnIndexOrThrow(MediaColumns.DATA);
			mCursor.moveToFirst();
			String path = mCursor.getString(column_index);
			return path;
		}
		return "";
	}

	/**
	 * 加载图片操作
	 * 
	 * <br>
	 * Created 2014-9-20 下午4:17:43
	 * 
	 * @version SendImageActivity
	 * @author HuangYK
	 * 
	 * @see
	 */
	private class LoadingBitmap extends ProgressTask {

		/**
		 * 实例化加载图片线程
		 * 
		 * Creates a new instance of LoadingBitmap. <br>
		 * Created 2014-9-20 下午4:17:48
		 * 
		 * @param context
		 *            上下文
		 * @param resId
		 *            提示语资源ID
		 */
		public LoadingBitmap(Context context, int resId) {
			super(context, resId);
			progressDialogIteration = new IProgressDialogIteration() {

				@Override
				public void onShow() {
					mPd.show();
				}

				@Override
				public void onDismiss() {
					if ((mPd != null) && (mPd.isShowing())) {
						mPd.dismiss();
					}
					if (isCancelled()) {
						mActivity.finish();
					}
				}
			};
		}

		@Override
		protected void doSuccess() {
			// 如果图片都获取不到，关闭
			if (mActivity == null || mActivity.isFinishing()) {
				return;
			}
			if (mThumbnail == null) {
				mActivity.finish();
				return;
			}

			initComponentValue();
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			if (mActivity == null || mActivity.isFinishing()) {
				return;
			}
			mActivity.finish();
		}

		@Override
		protected Integer doInBackground(Void... params) {
			if (getBitmapFromUri()) {
				return 0;
			}
			return -1;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCursor != null) {
			mCursor.close();
			mCursor = null;
		}
	}
}